package com.api.backend.service.impl.rpc;

import com.api.backend.common.ErrorCode;
import com.api.backend.exception.BusinessException;
import com.api.backend.mapper.UserInterfaceInfoMapper;
import com.api.backend.service.UserInterfaceInfoService;
import com.api.common.entity.UserInterfaceInfo;
import com.api.common.service.RpcUserInterfaceInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;

@DubboService
public class RpcUserInterfaceInfoServiceImpl implements RpcUserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    /**
     * 判断接口是否还有调用次数
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean hasInvokeCount(long interfaceInfoId, long userId) {
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceInfoId",interfaceInfoId);
        queryWrapper.eq("userId",userId);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoMapper.selectOne(queryWrapper);
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //剩余接口调用次数
        int leftNum = userInterfaceInfo.getLeftNum();
        return leftNum > 0;
    }

    /**
     * 根据userId、interfaceInfoId,把接口剩余调用次数 -1 ，总调用次数 +1
     *
     * @param userId          用户id
     * @param interfaceInfoId 接口id
     * @return boolean
     */
    @Override
    public boolean changeInvokeCount(long interfaceInfoId, long userId) {
        return userInterfaceInfoService.invokeCount(interfaceInfoId,userId);
    }
}
